/*
 *  The MIT License
 *
 * Copyright (c) 2010, Seiji Sogabe
 * 
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 * 
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 * 
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *  THE SOFTWARE.
 */
package hudson.plugins.googlecodetrigger;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Logger;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.codec.binary.Hex;

/**
 * Goolecode Project Hosting Hook HMAC.
 *
 * @see http://code.google.com/p/support/wiki/PostCommitWebHooks#Authentication
 * @author sogabe
 */
public class GooglecodeHookHMAC {

    private final String secret;

    public GooglecodeHookHMAC(String secret) {
        this.secret = secret;
    }

    /**
     * Validate HMAC.
     * 
     * @param req {@link HttpServletRequest}
     * @return <code>true</code> if HMAC is valid.
     */
    public boolean validate(HttpServletRequest req) {
        if (req == null) {
            return false;
        }
        String payload = getPayload(req);
        String expectedHash = req.getHeader("Google-Code-Project-Hosting-Hook-Hmac");
        
        LOGGER.fine("Authentication Key: " + secret);
        LOGGER.fine("payload: " + payload);
        LOGGER.fine("expectedHash: " + expectedHash);

        byte[] digest;
        try {
            Key key = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacMD5");
            Mac mac = Mac.getInstance(key.getAlgorithm());
            mac.init(key);
            digest = mac.doFinal(payload.getBytes("UTF-8"));
        } catch (InvalidKeyException ex) {
            LOGGER.warning(ex.getMessage());
            return false;
        } catch (UnsupportedEncodingException ex) {
            LOGGER.warning(ex.getMessage());
            return false;
        } catch (NoSuchAlgorithmException ex) {
            LOGGER.warning(ex.getMessage());
            return false;
        }

        String calculatedHash = new String(Hex.encodeHex(digest));
        LOGGER.fine("calculatedHash: " + calculatedHash);
        return calculatedHash.equals(expectedHash);
    }

    private String getPayload(HttpServletRequest req) {
        BufferedReader r = null;
        StringBuilder payload = new StringBuilder();
        try {
            r = req.getReader();
            String line;
            while (true) {
                line = r.readLine();
                if (line == null) {
                    break;
                }
                payload.append(line);
            }
        } catch (IOException e) {
            LOGGER.warning(e.getMessage());
        } finally {
            closeQuietly(r);
        }
        return payload.toString();
    }

    private void closeQuietly(Closeable c) {
        if (c == null) {
            return;
        }
        try {
            c.close();
        } catch (IOException e) {
            LOGGER.warning(e.getMessage());
        }
    }

    private static final Logger LOGGER = Logger.getLogger(GooglecodeHookHMAC.class.getName());
}
